package expression.primary;

import java.util.List;

import util.Reference;
import util.Result;
import util.Scope;
import util.Selector;
import util.Type;
import exception.ExpressionException;
import expression.PrimaryExpression;

public class Ident extends PrimaryExpression{
	private String name; // name != "" - Ident is variable
	private List<Selector> selectors;
//	private Reference reference;
	
	public Reference getReference() {
		return scope.getReference(name);//reference;
	}

	public void setReference(Reference reference) {
		this.scope.addReference(reference);//this.reference = reference;
	}

	public String getName() {
		return name;
	}
	
	public List<Selector> getSelectors() {
		return selectors;
	}
	
	public Ident(Scope scope) {
		super(scope);
		//TODO
	}
	
	public Ident(Scope scope, String name, List<Selector> selectors) {
		this(scope, name, selectors, null);
	}
	
	public Ident(Scope scope, String name, List<Selector> selectors, Reference variable) {
		super(scope);
		this.name = name;
		this.selectors = selectors;
		if(variable!=null){
			this.scope.addReference(variable);// TODO jesli jeszcze nie ma
		}
//		this.reference = variable;
		if(selectors.size() > 0){
			if(selectors.get(0).getType().compareTo("index") == 0){
				this.result = new Result(new Type(scope.getReference(name).getType().getName(), false), null);
			}
		
		}else{
			this.result = new Result(scope.getReference(name).getType(), null);
		}
	}

	@Override
	public Result evaluate() throws ExpressionException {
		// TODO Auto-generated method stub
		//result.getType().isArray()
		if(selectors.size() > 0){
			if(selectors.get(0).getType().compareTo("index") == 0){
				Result[] array = (Result[])getReference().getValue();
				Result res = array[(Integer)selectors.get(0).getValue()];
				this.result.setValue(res.getValue());
			}
		}else{
			this.result.setValue(getReference().getValue());
		}
//		this.result.setValue(this.reference.getValue());
		return this.result;
	}
	
	public String toString() {
		return "Ident: [ name: "+ this.name + ", result: " + this.result + ", selectors: " + this.selectors+ "]";
	}
	
}
